let canShowSpeaker = false;
const speakerContent: Array<(value?: void | PromiseLike<void>) => void> = [];
const mainScreen = UiScreen.getAllScreen().find((e) => e.name === 'screen');
// 主讲框
interface SpeakerParams {
    name: string;
    avatar: string;
    userId: string;
    text: string;
    type: string;
}

async function showSpeaker({
    name,
    avatar,
    userId,
    text,
    type,
}: SpeakerParams) {
    if (canShowSpeaker) {
        await new Promise<void>((resolve) => {
            speakerContent.push(resolve);
        });
    }
    const mainBox = mainScreen?.findChildByName('主讲框');
    if (!mainBox) {
        return;
    }
    mainBox.visible = true;

    const Type = mainBox?.findChildByName('Type') as UiText;
    if (Type) {
        Type.textContent = type;
    }

    const PlayerData = mainBox.findChildByName('PlayerData');
    if (!PlayerData) {
        mainBox.visible = false;
        return;
    }

    const Avatar = PlayerData.findChildByName('Avatar')?.findChildByName(
        'image'
    ) as UiImage;
    if (Avatar) {
        Avatar.image = avatar;
    }

    const Name = PlayerData.findChildByName('Name') as UiText;
    if (Name) {
        Name.textContent = name + '  (' + userId + ')';
    }

    const Content = mainBox?.findChildByName('Content');
    const Text = Content?.findChildByName('text') as UiText;
    if (Text) {
        Text.textContent = text;
    }

    canShowSpeaker = true;
    for (let i = 0; i < text.length; i++) {
        Text.textContent = '    ' + text.slice(0, i + 1);
        await sleep(64);
    }
    await sleep(1000 + (Text.textContent.length / 50) * 1000);
    if (speakerContent.length > 0) {
        speakerContent[0]();
        speakerContent.splice(0, 1);
    } else {
        canShowSpeaker = false;
    }
    mainBox.visible = false;
}

export { showSpeaker };
